package handler

import (
	"github.com/gin-gonic/gin"
	"go-devops/common"
	"go-devops/domain/dto"
	"go-devops/domain/model"
	"go-devops/domain/vo"
)

func UserList(c *gin.Context) {
	list, err := model.QueryUserList()
	if err != nil {
		common.BizError(c, "查询失败")
		return
	}

	resultList := make([]*vo.UserVO, 0)
	for _, user := range list {
		userVO := &vo.UserVO{
			Id:         user.Id,
			Username:   user.Username,
			Status:     user.Status,
			UpdateTime: user.UpdateTime,
			CreateTime: user.CreateTime,
		}
		resultList = append(resultList, userVO)
	}
	common.OKData(c, resultList)
}

func AddUser(c *gin.Context) {
	var addUser dto.AddUserDTO
	if err := c.ShouldBindJSON(&addUser); err != nil {
		common.BizError(c, err.Error())
		return
	}

	// 查询用户是否已存在
	count, err := model.QueryUserCount(addUser.Username)
	if err != nil {
		common.BizError(c, "添加失败")
		return
	}

	if count > 0 {
		common.BizError(c, "用户已存在")
		return
	}

	hashPassword, err := common.HashPassword(addUser.Password)
	if err != nil {
		common.BizError(c, "密码加密失败")
		return
	}

	user := &model.User{
		Username:   addUser.Username,
		Password:   hashPassword,
		Status:     common.UserNormal.Status,
		UpdateTime: common.NowStr(),
		CreateTime: common.NowStr(),
	}

	if err := model.AddUser(user); err != nil {
		common.BizError(c, "添加用户失败")
		return
	}
	common.OK(c)
}
